package com.controller.teachers;

import com.bean.entity.*;
import com.bean.pojo.*;
import com.bean.util.DtoUtil;
import com.bean.vo.*;
import com.service.*;
import com.service.impl.TransScoreToEnrollmentRate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("teacher")
public class TeachersController {
    @Autowired
    private TeachersService teachersService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private StudentScoreService studentScoreService;
    @Autowired
    private PhysicalHealthService physicalHealthService;
    @Autowired
    private DormitoryService dormitoryService;
    @Autowired
    private StudentCommunicationService studentCommunicationService;
    @Autowired
    private StudentCommentService studentCommentService;
    @Autowired
    private TransAddressService transAddressService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private SubjectInfoService subjectInfoService;
    @Autowired
    private UtilService utilService;
    @Autowired
    private TestInfoService testInfoService;
    @Autowired
    private StudentScoreStatisticalService studentScoreStatisticalService;
    @Autowired
    private TransScoreToEnrollmentRate transScoreToEnrollmentRate;

    /**教师对学生的增删改查*/
    @RequestMapping("queryAllStu")
    public Dto queryAllStu(Integer page, Integer limit, PageAssistant<StudentInfoVo> pa, String keyword){
        System.out.println("...查询所有学生");

        System.out.println(keyword);

        if(page != null){
            pa.setCurrPage(page);
            pa.setPageSize(limit);
        }

        Map<String ,Object> map= new HashMap<String,Object>();
        map.put("keyword",keyword);

        pa = studentInfoService.queryByPage(map, pa);

        for (int i = 0; i <pa.getItems().size() ; i++) {
                if (pa.getItems().get(i).getAddress()!=null){
                    pa.getItems().get(i).setAddress(transAddressService.transAddress(pa.getItems().get(i).getAddress()));
                }
                if (pa.getItems().get(i).getBornplace()!=null){
                    pa.getItems().get(i).setBornplace(transAddressService.transAddress(pa.getItems().get(i).getBornplace()));
                }
                if (pa.getItems().get(i).getNativePlace()!=null){
                    pa.getItems().get(i).setNativePlace(transAddressService.transAddress(pa.getItems().get(i).getNativePlace()));
                }
            }
        return DtoUtil.returnSuccess(pa);

//        try {
//            pa = studentInfoService.queryByPage(map, pa);
////            List<StudentInfoVo> queryAllStuInfo = studentInfoService.query(new StudentInfo());
//
//            for (int i = 0; i <pa.getItems().size() ; i++) {
//                if (pa.getItems().get(i).getAddress()!=null){
//                    pa.getItems().get(i).setAddress(transAddressService.transAddress(pa.getItems().get(i).getAddress()));
//                }
//                if (pa.getItems().get(i).getBornplace()!=null){
//                    pa.getItems().get(i).setBornplace(transAddressService.transAddress(pa.getItems().get(i).getBornplace()));
//                }
//                if (pa.getItems().get(i).getNativePlace()!=null){
//                    pa.getItems().get(i).setNativePlace(transAddressService.transAddress(pa.getItems().get(i).getNativePlace()));
//                }
//            }
//
////            pa.setItems(queryAllStuInfo);
////            pa.setCount(queryAllStuInfo.size());
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return DtoUtil.returnSuccess(pa);
    }
    @RequestMapping("teacherAddStu")
    public Dto teacherAddStu(StudentInfo studentInfo, AddressInfo addressInfo){
        System.out.println("...增加学生");
        System.out.println(studentInfo);
        System.out.println("...页面地址信息"+addressInfo);

        //家庭住址
        String address=addressInfo.getProvice()+"0"+addressInfo.getCity()+"0"+addressInfo.getDistrict()+
                addressInfo.getStreet()+addressInfo.getVillage();

        //出生地地址
        String bornPlace=addressInfo.getBornProvice()+"0"+addressInfo.getBornCity()+"0"+addressInfo.getBornDistrict()+
                addressInfo.getBornStreet()+addressInfo.getBornVillage();

        //籍贯地址
        String nativePlace=addressInfo.getNativeProvice()+"0"+addressInfo.getNativeCity()+"0"+addressInfo.getNativeDistrict()+
                addressInfo.getNativeStreet()+addressInfo.getNativeVillage();

        studentInfo.setAddress(address);
        studentInfo.setBornplace(bornPlace);
        studentInfo.setNativePlace(nativePlace);
        try {
            studentInfoService.save(studentInfo);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("modifyStu")
    public Dto teacherModifyStu(StudentInfo studentInfo){
        System.out.println("...修改学生");
        System.out.println(studentInfo);

        try {
            studentInfoService.modify(studentInfo);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("deleteStu")
    public Dto teacherDeleteStu(StudentInfo studentInfo){
        System.out.println("...删除学生");
        System.out.println(studentInfo);

        try {
            studentInfoService.remove(studentInfo);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

    /** 教师对学生成绩的增删改查 */
    @RequestMapping("queryStuScore")
    public Dto queryStuScore(Integer page,Integer limit, HttpServletRequest request, PageAssistant<StudentScoreVo> pa){
        System.out.println("...查询所带学生成绩");
        Integer teacherId=(Integer)request.getSession().getAttribute("loginTeacherId");
        System.out.println("登录老师id是"+teacherId);
        pa.setCurrPage(page);
        pa.setPageSize(limit);
        try {
            //查询学生成绩表中科目老师相同的信息
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("teacherId",teacherId);
            PageAssistant<StudentScoreVo> studentScorePa = studentScoreService.queryByPage(map, pa);
            return DtoUtil.returnSuccess(studentScorePa);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
   @RequestMapping("addStuScore")
   public Dto addStuScore(StudentScore studentScore){
       System.out.println("...增加学生分数记录");
       System.out.println(studentScore);
       try {
           studentScoreService.save(studentScore);
           return DtoUtil.returnSuccess();
       } catch (Exception e) {
           e.printStackTrace();
           return DtoUtil.returnFail(e.getMessage());
       }
   }
    @RequestMapping("modifyStuScore")
   public Dto modifyStuScore(StudentScore studentScore){
       System.out.println("...修改学生分数信息");
       System.out.println(studentScore);

       try {
           studentScoreService.modify(studentScore);
           return DtoUtil.returnSuccess();
       } catch (Exception e) {
           e.printStackTrace();
           return DtoUtil.returnFail(e.getMessage());
       }
   }
    @RequestMapping("deleteStuScore")
   public Dto deleteStuScore(StudentScore studentScore){
       System.out.println("...删除学生成绩记录");
       System.out.println(studentScore);

       try {
           studentScoreService.remove(studentScore);
           return DtoUtil.returnSuccess();
       } catch (Exception e) {
           e.printStackTrace();
           return DtoUtil.returnFail(e.getMessage());
       }
   }

    @RequestMapping("queryAllStuScore")
    public Dto queryAllStuScore(Integer page,Integer limit,PageAssistant<StudentScoreVo> scorePa,String classesId,
            String startTime,String endTime,String keyword,String subjectId,String teacherId,String lowScore,
            String highScore,PageAssistant<StudentInfoVo> studentPa){
        System.out.println("...查询所有学生成绩");
        System.out.println("关键字是"+keyword+"起始时间"+startTime+"终止时间"+endTime+"班级id是"+classesId+
                "科目是"+subjectId+"老师id是"+teacherId+"查询的最低分是"+lowScore+"查询的最高分是"+highScore);

//        //添加数据
//        utilService.AddScoreUtil(300);

        scorePa.setCurrPage(page);
        scorePa.setPageSize(limit);

        //创建查询学生姓名的参数集合
        Map<String,Object> mapStuInfo=new HashMap<String, Object>();

        //创建学生成绩的查询参数集合
        Map<String,Object> mapScore=new HashMap<String, Object>();
        if (classesId!=null && !classesId.equals("")){
            mapScore.put("classesId",Long.valueOf(classesId));
        }
        if (startTime!=null){
            mapScore.put("startTime",startTime);
        }
        if (endTime!=null){
            mapScore.put("endTime",endTime);
        }
        if (subjectId!=null && !subjectId.equals("")){
            mapScore.put("subjectId",Integer.valueOf(subjectId));
        }
        if (teacherId!=null && !teacherId.equals("")){
            mapScore.put("teacherId",Integer.valueOf(teacherId));
        }
        if (lowScore!=null && !lowScore.equals("")){
            mapScore.put("lowScore",lowScore);
        }
        if (highScore!=null && !highScore.equals("")){
            mapScore.put("highScore",highScore);
        }

        if (keyword!=null && !keyword.trim().equals("")){
            List<StudentScoreVo> studentScoreList=new ArrayList<StudentScoreVo>();
            mapStuInfo.put("keyword",keyword);
            List<StudentInfoVo> studentItems = studentInfoService.queryByPage(mapStuInfo, studentPa).getItems();
            for (int i = 0; i <studentItems.size() ; i++) {
                mapScore.put("studentId",studentItems.get(i).getId());
                PageAssistant<StudentScoreVo> allStuScore = studentScoreService.queryByPage(mapScore, scorePa);
                if (allStuScore.getItems().size()!=0){
                    studentScoreList.add(allStuScore.getItems().get(i));
                }
            }
            scorePa.setItems(studentScoreList);
            scorePa.setCount(studentScoreList.size());
            return DtoUtil.returnSuccess(scorePa);
        }

        //如果没有姓名参数，则直接查询
        PageAssistant<StudentScoreVo> allStuScore = studentScoreService.queryByPage(mapScore, scorePa);
        return DtoUtil.returnSuccess(allStuScore);
    }

    @RequestMapping("queryAllPhy")
    public Dto queryAllPhy(HttpServletRequest request,Integer page,Integer limit,PageAssistant<PhysicalHealthVo> pa){
        System.out.println("...查询所有学生的体质健康");
        pa.setCurrPage(page);
        pa.setPageSize(limit);

        //获取登录老师的id
        Integer teacherId=(Integer) request.getSession().getAttribute("loginTeacherId");
        System.out.println(teacherId);
        //通过老师id查找所带的学生id
        try {
            List<StudentInfoVo> queryStuId = studentInfoService.query(new StudentInfo(null,teacherId));

            System.out.println("通过老师id查到的学生信息"+queryStuId);
            //通过查到的学生信息，循环遍历查询体质健康信息，并放入集合中
            List<PhysicalHealthVo> sameTeacherPhyInfo=new ArrayList<PhysicalHealthVo>();

            int count=0;
            for (int i = 0; i < queryStuId.size(); i++) {
                List<PhysicalHealthVo> physicalHealthVo = physicalHealthService.query(new PhysicalHealth(queryStuId.get(i).getId()));
                if (physicalHealthVo.size()==1){
                    sameTeacherPhyInfo.add(physicalHealthVo.get(0));
                    count++;
                }
            }
            System.out.println(sameTeacherPhyInfo);

            pa.setItems(sameTeacherPhyInfo);
            pa.setCount(count);
            return DtoUtil.returnSuccess(pa);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

    /** 负责宿舍管理的老师进行增删改查 */
    @RequestMapping("queryChargeDormitory")
    public Dto queryDormitoryInfo(HttpServletRequest request, PageAssistant<DormitoryVo> pa){
        System.out.println("...查询负责的宿舍学生信息");
        Integer teacherId=(Integer)request.getSession().getAttribute("loginTeacherId");
        System.out.println(teacherId);

        try {
            List<DormitoryVo> dormitoryInfoList = dormitoryService.query(new Dormitory(null,teacherId));
            pa.setItems(dormitoryInfoList);
            pa.setCount(dormitoryInfoList.size());
            return DtoUtil.returnSuccess(pa);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("modifyStuDormitory")
    public Dto modifyStuDormitory(Dormitory dormitory){
        System.out.println("...修改宿舍信息");
        System.out.println(dormitory);

        try {
            dormitoryService.modify(dormitory);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("deleteStuDormitory")
    public Dto deleteStuDormitory(Dormitory dormitory){
        System.out.println("...删除宿舍信息");
        System.out.println(dormitory);

        try {
            dormitoryService.remove(dormitory);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("addStuDormitory")
    public Dto addStuDormitory(Dormitory dormitory){
        System.out.println("...新增宿舍信息");
        System.out.println(dormitory);

        try {
            dormitoryService.save(dormitory);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

    /**管理员功能*/
    @RequestMapping("queryTeacher")
    public Dto teacherQueryStudent(PageAssistant<TeachersVo> pa, HttpServletRequest request){
        System.out.println("...查询登录的老师个人信息");
        Integer teacherId=(Integer)request.getSession().getAttribute("loginTeacherId");
        System.out.println(teacherId);

        try {
            List<TeachersVo> queryLoginTeacherInfo = teachersService.query(new Teachers(teacherId));
            //将地址从字符串的数字转化成字符串的文字
            queryLoginTeacherInfo.get(0).setAddress(transAddressService.transAddress(queryLoginTeacherInfo.get(0).getAddress()));
            pa.setItems(queryLoginTeacherInfo);
            return DtoUtil.returnSuccess(pa);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("modifyTeacher")
    public Dto modifyTeacher(Teachers teachers){
        System.out.println("...修改老师信息");
        System.out.println(teachers);
        try {
            teachersService.modify(teachers);
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

//    @RequestMapping("login")
    public Dto teacherLogin(Teachers teachers,HttpSession session){
        System.out.println("...教师登录");
        System.out.println(teachers);

        try {
            TeachersVo teacherLogin = teachersService.teacherLogin(teachers);
            session.setAttribute("loginTeacherId",teacherLogin.getId());
            return DtoUtil.returnSuccess("登录成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

    /**教师与学生的交流沟通*/
    @RequestMapping("communication")
    public Dto communication(HttpServletRequest request, HttpSession session, Integer page,Integer limit, PageAssistant<StudentCommunicationVo> pa ) {
        System.out.println(">>>园丁之声>>>学生交流");

        Integer teacherId=(Integer)request.getSession().getAttribute("loginTeacherId");

        pa.setCurrPage(page);
        pa.setPageSize(limit);

        Map<String,Object> map=new HashMap<String,Object>();

        map.put("teacherId",teacherId);

        PageAssistant<StudentCommunicationVo> studentCommunication = studentCommunicationService.queryByPage(map, pa);

        return  DtoUtil.returnSuccess(studentCommunication);

    }

    @RequestMapping("comment")
    public Dto comment(HttpServletRequest request, HttpSession session, Integer page,Integer limit, PageAssistant<StudentCommentVo> pa ) {
        System.out.println(">>>园丁之声>>>学生评价");

        Integer teacherId=(Integer)request.getSession().getAttribute("loginTeacherId");

        pa.setCurrPage(page);
        pa.setPageSize(limit);

        Map<String,Object> map=new HashMap<String,Object>();

        map.put("teacherId",teacherId);

        PageAssistant<StudentCommentVo> studentComment = studentCommentService.queryByPage(map, pa);

        return  DtoUtil.returnSuccess(studentComment);

    }

    /**管理员部分*/

    /*全校学生统计表功能*/
    @RequestMapping("schoolScoreStatistical")
    public Dto schoolScoreStatistical(Integer page,Integer limit,PageAssistant<StudentScoreStatisticalVo> pa
            ,InputEnrollmentInfo inputEnrollmentInfo) throws Exception {
        System.out.println("...查询全校学生成绩统计表");
        System.out.println("...页面传递的参数"+inputEnrollmentInfo);
        pa.setPageSize(limit);
        pa.setCurrPage(page);

        List<StudentScoreStatisticalVo> querySSS = studentScoreStatisticalService.query(new StudentScoreStatistical());
        if (querySSS.size()!=0){
            for (int i = 0; i <querySSS.size() ; i++) {
                studentScoreStatisticalService.remove(new StudentScoreStatistical(i+1));
            }
            transScoreToEnrollmentRate.transScoreToEnrollmentRate();
        }

        Map<String,Object> map=new HashMap<String, Object>();

        if (inputEnrollmentInfo.getClassesId()!=null && !inputEnrollmentInfo.getClassesId().equals("")){
            map.put("classesId",inputEnrollmentInfo.getClassesId());
        }
        if (inputEnrollmentInfo.getLowScore()!=null && !inputEnrollmentInfo.getLowScore().equals("")){
            map.put("lowScore",inputEnrollmentInfo.getLowScore());
        }
        if (inputEnrollmentInfo.getHighScore()!=null && !inputEnrollmentInfo.getHighScore().equals("")){
            map.put("highScore",inputEnrollmentInfo.getHighScore());
        }
        if (inputEnrollmentInfo.getTestId()!=null && !inputEnrollmentInfo.getTestId().equals("")){
            List<TestInfo> queryTestTime = testInfoService.query(new TestInfo(inputEnrollmentInfo.getTestId()));
            map.put("testTime",queryTestTime.get(0).getTestTime());
        }

        PageAssistant<StudentScoreStatisticalVo> sssPa = studentScoreStatisticalService.queryByPage(map, pa);

//        if (inputEnrollmentInfo.getClassesId()==null &&
//                inputEnrollmentInfo.getGradeId()!=null &&
//                !inputEnrollmentInfo.getGradeId().equals("")){
//            Date now =new Date();
//            int nowYear=now.getYear()+1900;
//            switch (inputEnrollmentInfo.getGradeId()){
//                case 1:
//                    break;
//                case 2:
//                    break;
//                case 3:
//
//                    break;
//            }
//        }
        return DtoUtil.returnSuccess(sssPa);
    }


    @RequestMapping("enrollmentRate")
    public Dto enrollmentRate(Integer page,Integer limit,InputEnrollmentInfo inputEnrollmentInfo
            ,PageAssistant<AllStudentScore> allScorePa,PageAssistant<StudentScoreVo> scorePa) throws Exception {
        System.out.println("...升学率分析");
        System.out.println("页面获得的参数"+inputEnrollmentInfo);

        /**将学生成绩表里的数据处理整合，输出到全校学生成绩统计表的表中*/
        List<StudentScoreStatisticalVo> querySSS = studentScoreStatisticalService.query(new StudentScoreStatistical());
        if (querySSS.size()!=0){
            for (int i = 0; i <querySSS.size() ; i++) {
                studentScoreStatisticalService.remove(new StudentScoreStatistical(i+1));
            }
            transScoreToEnrollmentRate.transScoreToEnrollmentRate();
        }

        //创建学生分数查询的参数集合
        Map<String,Object> map=new HashMap<String, Object>();

        if (inputEnrollmentInfo.getClassesId()!=null){
            map.put("classesId",inputEnrollmentInfo.getClassesId());
        }
        if (inputEnrollmentInfo.getSubjectId()!=null){
            map.put("subjectId",inputEnrollmentInfo.getSubjectId());
        }
        if (inputEnrollmentInfo.getTeacherId()!=null){
            map.put("teacherId",inputEnrollmentInfo.getTeacherId());
        }
        //查询符合上面条件的总记录数
        List<StudentScoreVo> studentScoreVoList = studentScoreService.queryByPage(map, scorePa).getItems();
        //把学生的数据处理。把学生id和学生的总分
        List<StudentScoreStatistical> transRateInfo=new ArrayList<StudentScoreStatistical>();
        //获取试卷信息集合
        List<TestInfo> testInfoList = testInfoService.query(new TestInfo());
        //获取学生信息集合
        List<StudentInfoVo> queryStudentInfo = studentInfoService.query(new StudentInfo());


        //查询班级信息
        List<ClassesVo> classesList = classesService.query(new Classes());

        int studentNum=0;
        int keyLineNum=0;
        int firstLineNum=0;
        int secondLineNum=0;

        //查询重点线的学生数量
        if (inputEnrollmentInfo.getKeyLine()!=null){
            for (int i = 0; i <studentScoreVoList.size() ; i++) {
                for (int j = 0; j <classesList.size() ; j++) {

                }
            }
        }
        return null;
    }


    /** 下拉框功能*/
    @RequestMapping("queryClass")
    public Dto queryClass(){
        System.out.println("...查询班级");
        try {
            List<ClassesVo> classList = classesService.query(new Classes());
            return DtoUtil.returnSuccess(classList);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("querySubject")
    public Dto querySubject(){

        System.out.println("...查询科目详情");
        try {
            return DtoUtil.returnSuccess(subjectInfoService.query(new SubjectInfo()));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }
    @RequestMapping("queryAllTeacherName")
    public Dto queryAllTeachers(){
        System.out.println("...查询所有老师");
        try {
            return DtoUtil.returnSuccess(teachersService.query(new Teachers()));

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage());
        }
    }

}
